﻿using System;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Text;
using Texfina.Core.Common;
using Texfina.Common.Mg;
using Texfina.Core.Web;
using Texfina.Core.Data;
using Texfina.Entity.Rh;
using Texfina.Entity.Mg;
using Texfina.Entity.Sy;
using RHBOQry = Texfina.BOQry.Rh;
using MGBOQry = Texfina.BOQry.Mg;
using RHBOMnt = Texfina.BOMnt.Rh;
using SYBOQry = Texfina.BOQry.Sy;

namespace RH
{
    public partial class wfPrograVacaMasiMnt : EditPage
    {

        #region Propiedades
        public int strPeriodoVac
        {
            get { return (int)this.ViewState["_strYear"]; }
            set { this.ViewState["_strYear"] = value; }
        }

        public DataTable DataSourceList
        {
            get { return (DataTable)this.ViewState["_dsList"]; }
            set { this.ViewState["_dsList"] = value; }
        }

        public DateTime FeInicio
        {
            get { return (DateTime)this.ViewState["_feini"]; }
            set { this.ViewState["_feini"] = value; }
        }

        public DateTime FeFin
        {
            get { return (DateTime)this.ViewState["_fefin"]; }
            set { this.ViewState["_fefin"] = value; }
        }

        #endregion

        public const int _GRDLIST_STANULADO = 5;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.IsPostBack)
            {
                this.LoadInPostBack();
                return;
            }
            this.LoadData();
        }

        public override void LoadInPostBack()
        {
            //scProgVaca.Width = int.Parse(hdnSCWidth.Value.ToString());
            //scProgVaca.Height = int.Parse(hdnSCHeight.Value.ToString());
            scProgVaca.SCDataList = this.DataSourceList;
            scProgVaca.SCDataSchuleder = this.DataSource;
            scProgVaca.SCFechaInicio = FeInicio; 
            scProgVaca.SCFechaFin = FeFin; 

            this.RegisterGeneralScripts();
        }

        public override void LoadInitialSettings()
        {
            Label lbl = (Label)this.Master.FindControl("lblTitle");
            lbl.Text = "Programación de Vacaciones";
            this.FormEditAction = (FormEditAction)Enum.Parse(typeof(FormEditAction), Request.QueryString["formEA"]);
            this.SetInitialTitle("Programación de Vacaciones");
        }

        public override void LoadListControls()
        {
            ETablaGenDet objEDet = new ETablaGenDet();

            IBOQuery objBOCCosto = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(MGBOQry.CCosto));
            MGBOQry.ITablaGen objBOI = (MGBOQry.ITablaGen)WCFHelper.GetObject<MGBOQry.ITablaGen>(typeof(MGBOQry.TablaGen));

            objEDet.IdTabla = ConstMultitabla.FORMA_PAGO;
            DataTable dt = objBOI.GetDetailByList(objEDet);
            WebHelper.LoadListControl(ddlidFormaPago, dt, "dsDescrip", "idCodigo");

        }

        public override void DataToControls()
        {
            strPeriodoVac = int.Parse(Session[ConstSessionVar.PERIODO].ToString()) - 1;
            lblYear.Text = strPeriodoVac.ToString();
            GetSchuleder_DataBinding();
            
        }

        public override void RegisterGeneralScripts()
        {
            txtidPersonal.Attributes.Add("readonly", "true");
            txtdsPersonal.Attributes.Add("readonly", "true");

            StringBuilder sb = new StringBuilder();


            sb.AppendLine("function validateEditForm(key){");

            sb.AppendLine("menu_doPostBack('" + mnuToolbar.ClientID + "','" + mnuToolbar.UniqueID + "',key);");
            sb.AppendLine("}");

            sb.AppendLine("function validateEditFormGrid(key){");
            sb.AppendLine("varRpta = isEmptyControl('" + this.txtfeIniGroup.ClientID + "','Ingrese el fecha de Inicio.');");
            sb.AppendLine("if(varRpta==true)");
            sb.AppendLine("return !varRpta;");
            sb.AppendLine("varRpta = isEmptyControl('" + this.txtfeFinGroup.ClientID + "','Ingrese el fecha de Fin.');");
            sb.AppendLine("if(varRpta==true)");
            sb.AppendLine("return !varRpta;");
            sb.AppendLine("menu_doPostBack('" + mnuGrid.ClientID + "','" + mnuGrid.UniqueID + "',key);");
            sb.AppendLine("}");

            ScriptManager.RegisterStartupScript(this, this.GetType(), "ScriptRegister", sb.ToString(), true);


            RegisterEditPopupScripts();
        }

        public void RegisterEditPopupScripts()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("function validate" + this.bttOkPopup.ID + "(){");
            sb.AppendLine("varRpta = isEmptyControl('" + this.txtfeInicio.ClientID + "','Seleccione la fecha de Inicio.');");
            sb.AppendLine("if(varRpta==true)");
            sb.AppendLine("return !varRpta;");
            sb.AppendLine("varRpta = isEmptyControl('" + this.txtfeFin.ClientID + "','Seleccione la fecha Final.');");
            sb.AppendLine("if(varRpta==true)");
            sb.AppendLine("return !varRpta;");
            sb.AppendLine("}");

            ScriptManager.RegisterStartupScript(this, this.GetType(), "validatePopup", sb.ToString(), true);

            this.bttOkPopup.OnClientClick = "return validate" + bttOkPopup.ID + "();";
            this.bttCancelPopup.OnClientClick = "$find('" + this.mdlPopup.ClientID + "').hide();return false;";
        }

        protected void mnuToolbar_MenuItemClick(Object sender, MenuEventArgs e)
        {
            if (e.Item == null)
                return;

            switch (e.Item.Value)
            {
                case ConstMenuToolbarValue.BUTTON_SAVE:
                case ConstMenuToolbarValue.BUTTON_SAVENEW:
                    if (this.FormEditAction != FormEditAction.Delete)
                        this.SaveData(e.Item.Value);
                    else
                        this.DeleteData();
                    break;

                case ConstMenuToolbarValue.BUTTON_EXIT:
                    this.Response.Redirect("wfPrograVacaBnd.aspx?Filter=1");
                    break;

            }

        }

        protected void mnuGrid_MenuItemClick(Object sender, MenuEventArgs e)
        {
            foreach (DataRow drList in this.DataSourceList.Rows)
            {
                Object objResNuSec = null;
                int intResNusec = 0;
                DataTable dt = (DataTable)this.DataSource;
                DataRow dr = null;

                objResNuSec = dt.Compute("MAX(nuSecuen)", "idPersonal=" + drList["idPersonal"].ToString());

                if (objResNuSec == null || objResNuSec.ToString() == "")
                    intResNusec = 0;
                else
                    intResNusec = Convert.ToInt32(objResNuSec);
                intResNusec += 1;

                dr = dt.NewRow();

                dr["nuSecuen"] = intResNusec;
                dr["idPersonal"] = drList["idPersonal"].ToString();
                dr["dsPersonal"] = drList["dsPersonal"].ToString();
                dr["feVacaIni"] = txtfeIniGroup.Text;
                dr["feVacaFin"] = txtfeFinGroup.Text;
                dr["stAnulado"] = ConstFlagEstado.DESACTIVADO;
                dt.Rows.Add(dr);

            }

        }
        
        protected void bttOkPopup_Click(object sender, EventArgs e)
        {
            Object objResNuSec = null;
            int intResNusec = 0;
            DataTable dt = (DataTable)this.DataSource;
            DataRow dr = null;


            //Object objNumDias = null;
            //int intNumDias = 0;
            //objResNuSec = dt.Compute("MAX(nuSecuen)", "idPersonal=" + txtidPersonal.Text);
            //if (objResNuSec == null || objResNuSec.ToString() == "")
            //    intResNusec = 0;
            //else
            //    intResNusec = Convert.ToInt32(objResNuSec);
            
            ////this.hdnMsgOPB.Value = this.CreatePostbackMessage(0, "NO VALIDO", "");
            ////return;

            objResNuSec = dt.Compute("MAX(nuSecuen)", "idPersonal=" + txtidPersonal.Text);
            if (objResNuSec == null || objResNuSec.ToString() == "")
                intResNusec = 0;
            else
                intResNusec = Convert.ToInt32(objResNuSec);
            intResNusec += 1;
            dr = dt.NewRow();
            dr["nuSecuen"] = intResNusec;
            dr["idPersonal"] = txtidPersonal.Text;
            dr["dsPersonal"] = txtdsPersonal.Text;
            dr["feVacaIni"] = txtfeInicio.Text;
            dr["feVacaFin"] = txtfeFin.Text;
            dr["stAnulado"] = ConstFlagEstado.DESACTIVADO;
            dt.Rows.Add(dr);

        }

        protected void bttBackYear_Click(object sender, EventArgs e)
        {
            strPeriodoVac = int.Parse(lblYear.Text) - 1;
            lblYear.Text = strPeriodoVac.ToString();
            GetSchuleder_DataBinding();
        }

        protected void bttNextYear_Click(object sender, EventArgs e)
        {
            strPeriodoVac = int.Parse(lblYear.Text) + 1;
            lblYear.Text = strPeriodoVac.ToString();
            GetSchuleder_DataBinding();
        }

        public override void LoadDataEditPopup(GridView grid, int rowIndex)
        {

        }

        public new void ClearEditPopup()
        {
        }

        public void LockControlsPopup()
        {

        }

        public override void SaveData(String key)
        {
            if (this.ValidateData() == false)
                return;

            IEntityBase objE = (IEntityBase)this.CreateEntitySet();


            IBOUpdate objPro = (IBOUpdate)WCFHelper.GetObject<IBOUpdate>(typeof(RHBOMnt.PerVacaProg));
            String[] strRet = objPro.UpdateData(objE);
            String strMsg = "";

            switch (this.FormEditAction)
            {

                case FormEditAction.AddNew:
                case FormEditAction.Copy:
                    strMsg = "Se ha registrado la Programacion de Vacaciones";
                    break;
                default:
                    strMsg = "Se ha modificado la Programacion de Vacaciones";
                    break;
            }
            this.hdnMsgOPB.Value = this.CreatePostbackMessage("CORRECTO", strMsg, TypeMessageAlert.correct, false, "wfPrograVacaBnd.aspx?Filter=1");


        }

        public override void DeleteData()
        {

        }

        public override Object CreateEntitySet()
        {
            DataTable dt = (DataTable)this.DataSource;
            this.ClearDeletedRow(this.DataSource, "stAnulado");
            IList<EPerVacaProg> colEVacaProg = new List<EPerVacaProg>();

            for (int intTypeUpd = 0; intTypeUpd <= 1; intTypeUpd++)
            {
                DataTable dtChange = null;
                if (intTypeUpd == 0)
                    dtChange = dt.GetChanges(DataRowState.Added);
                else
                    dtChange = dt.GetChanges(DataRowState.Modified);


                if (dtChange != null)
                {
                    foreach (DataRow dr in dtChange.Rows)
                    {
                        EPerVacaProg objEDet = new EPerVacaProg();
                        objEDet.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
                        objEDet.IdPersonal = dr["idPersonal"].ToString();
                        objEDet.IdPeriVac = strPeriodoVac.ToString();
                        objEDet.NuSecuen = int.Parse(dr["nuSecuen"].ToString());
                        objEDet.IdForPago = ddlidFormaPago.SelectedItem.Value;
                        objEDet.IdPlanilla = Request.QueryString["IdPlanilla"];
                        objEDet.IdConRemu = ConstConceptoRemu.VACACIONES;
                        objEDet.NuDiasVaca = (DateTime.Parse(dr["feVacaFin"].ToString()) - DateTime.Parse(dr["feVacaIni"].ToString())).Days + 1;
                        objEDet.MtVaca = 0;
                        objEDet.IdPeriAnualIni = DateTime.Parse(dr["feVacaIni"].ToString()).Year.ToString();
                        objEDet.NuProcAnualIni = DateTime.Parse(dr["feVacaIni"].ToString()).Month;
                        objEDet.FeVacaIni = DateTime.Parse(dr["feVacaIni"].ToString());
                        objEDet.IdPeriAnualFin = DateTime.Parse(dr["feVacaFin"].ToString()).Year.ToString();
                        objEDet.NuProcAnualFin = DateTime.Parse(dr["feVacaFin"].ToString()).Month;
                        objEDet.FeVacaFin = DateTime.Parse(dr["feVacaFin"].ToString());
                        objEDet.NuDiasGozado = 0;
                        objEDet.StVaca = ConstFlagEstado.DESACTIVADO;
                        objEDet.StAnulado = ConstFlagEstado.DESACTIVADO;

                        if (dr.RowState == DataRowState.Added)
                            objEDet.EntityState = EntityState.Added;

                        if (dr.RowState == DataRowState.Modified)
                        {
                            if (objEDet.StAnulado == ConstFlagEstado.DESACTIVADO)
                                objEDet.EntityState = EntityState.Modified;
                            else
                                objEDet.EntityState = EntityState.Deleted;
                        }

                        colEVacaProg.Add(objEDet);
                    }
                }
            }

            EPerVacaSet objESet = new EPerVacaSet();
            objESet.ColVacaProg = colEVacaProg;

            return objESet;
        }

        public override void LockControls()
        {

        }

        public void GetSchuleder_DataBinding()
        {

            EPerVacaProg objE = new EPerVacaProg();
            RHBOQry.IPersonal objBO = (RHBOQry.IPersonal)WCFHelper.GetObject<RHBOQry.IPersonal>(typeof(RHBOQry.Personal));
            objE.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
            objE.IdPersonal = Request.QueryString["IdPersonal"];
            objE.IdPeriVac = strPeriodoVac.ToString();
            DataTable dt = objBO.GetVacaPersonalGrupal(objE);
            this.DataSourceList = dt;
            scProgVaca.SCDataList = this.DataSourceList;

               FeInicio = new DateTime(strPeriodoVac + 1, 1, 1);
                scProgVaca.SCFechaInicio = FeInicio;
                txtfeInicio.DateMin = scProgVaca.SCFechaInicio.AddDays(-1);
                txtfeIniGroup.DateMin = scProgVaca.SCFechaInicio.AddDays(-1);
                txtfeFin.DateMin = scProgVaca.SCFechaInicio.AddDays(-1);
                txtfeFinGroup.DateMin = scProgVaca.SCFechaInicio.AddDays(-1);
            
                FeFin = new DateTime(strPeriodoVac + 1, 12, 31);
                scProgVaca.SCFechaFin = FeFin;
                txtfeInicio.DateMax = scProgVaca.SCFechaFin;
                txtfeIniGroup.DateMax = scProgVaca.SCFechaFin;
                txtfeFin.DateMax = scProgVaca.SCFechaFin;
                txtfeFinGroup.DateMax = scProgVaca.SCFechaFin;
   

            EPerVacaProg objEDet = new EPerVacaProg();
            RHBOQry.IPerVacaProg objBODet = (RHBOQry.IPerVacaProg)WCFHelper.GetObject<RHBOQry.IPerVacaProg>(typeof(RHBOQry.PerVacaProg));
            objEDet.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
            objEDet.IdPersonal = Request.QueryString["IdPersonal"];
            objEDet.IdPeriVac = strPeriodoVac.ToString();
            objEDet.IdForPago = ddlidFormaPago.SelectedItem.Value;
            dt = objBODet.GetProgVacaGrupal(objEDet);
            this.DataSource = dt;
            scProgVaca.SCDataSchuleder = this.DataSource;
        }

    }
}